package bpel.variables;

import java.util.HashMap;

import org.dom4j.Document;

import bpel.types.BPELType;

/**
 * 
 * @author Maurice & Topia
 * 
 */
public class BPELComplexVariable extends BPELVariable {

	private BPELType complexType;
	private String name;
	private HashMap<String, BPELVariable> subVars;

	public BPELComplexVariable(BPELType complexType, String name, HashMap<String, BPELVariable> subVars) {
		this.complexType = complexType;
		this.name = name;
		this.subVars = subVars;
	}

	public String query(String query) {

		if (query == null || query.equals("")) {
			System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
			return null;
		}

		if (query.contains("//")) {

			BPELVariable var = subVars.get(query.substring(2));

			if (var == null) {
				System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
				return null;
			} else {
				return var.query(null);
			}
		} else {
			String[] queryParts = query.split("/");
			int goodInd;

			if (queryParts[0].equals("")) {
				goodInd = 1;
			} else {
				goodInd = 0;
			}

			BPELVariable var = subVars.get(queryParts[goodInd]);

			if (var == null) {
				System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
				return null;
			} else {
				String newQuery = "";

				for (int i = goodInd + 1; i < queryParts.length; i++) {
					newQuery += "/" + queryParts[i];
				}

				return var.query(newQuery);
			}
		}
	}

	@Override
	public void set(String query, String value) {
		if (query == null || query.equals("")) {
			System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
		}

		if (query.contains("//")) {

			BPELVariable var = subVars.get(query.substring(2));

			if (var == null) {
				System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
			} else {
				var.set(null, value);
			}

		} else {
			String[] queryParts = query.split("/");
			int goodInd;

			if (queryParts[0].equals("")) {
				goodInd = 1;
			} else {
				goodInd = 0;
			}

			BPELVariable var = subVars.get(queryParts[goodInd]);

			if (var == null) {
				System.err.println("(BPELComplexVariable) Bad query on " + name + " : " + query);
			} else {
				String newQuery = "";

				for (int i = goodInd + 1; i < queryParts.length; i++) {
					newQuery += "/" + queryParts[i];
				}

				var.set(newQuery, value);
			}
		}
	}

	@Override
	public String toString() {
		return complexType.getName() + " : " + name;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void parse(String XMLDescription) {
		for (String varName : subVars.keySet()) {
			subVars.get(varName).parse(XMLDescription);
		}
	}

	@Override
	public Document getXMLDescription() {
		System.out.println("TODO implement BPELComplexVariable getXMLDescriprion method");
		
		for (String varName : subVars.keySet()) {
			subVars.get(varName).getXMLDescription();
		}
		
		return null;
	}
}
